package com.boot.unity.api.filter;

import com.alibaba.fastjson.JSON;
import com.boot.unity.api.common.ResponseResult;
import com.boot.unity.api.common.Result;
import com.boot.unity.api.common.ResultCodeEnum;
import com.boot.unity.api.constants.Constants;
import com.boot.unity.api.utils.IpUtil;
import com.boot.unity.api.utils.RedisUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.annotation.Order;
//import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Slf4j
@Order(2)
//@Component
@RequiredArgsConstructor
@ConditionalOnProperty(name = "spring.profiles.active",havingValue = "prod")
public class RepeatFilter extends OncePerRequestFilter {
//    private final RedisTemplate<String,Long> redisTemplate;
    @Value("${api.time.scope:5}")
    private int timeScope;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        /*AntPathMatcher matcher = new AntPathMatcher();
        String uri = request.getRequestURI();
        if (matcher.match(Constants.API_URI_PREFIX,uri)){
            long ts = Long.valueOf(request.getParameter("ts").trim());
            String key = RedisUtil.URI_PREFIX+uri+"_"+ts;
            Long cacheTs = redisTemplate.boundValueOps(key).get();
            if ((cacheTs == null) || (ts != cacheTs.longValue())){
                redisTemplate.boundValueOps(key).set(ts,timeScope, TimeUnit.MINUTES);
                filterChain.doFilter(request,response);
            }else {
                log.error("时间戳重复，请求接口：{}，请求IP：{}，请求参数：{}",
                        timeScope,
                        uri,
                        IpUtil.getIpAddress(request),
                        JSON.toJSONString(request.getParameterMap()));
                Result result = new Result(ResultCodeEnum.TIMESTAMP_REPEAT_OR_ERROR);
                ResponseResult.toJsonResult(response,result);
            }
        }else {
            filterChain.doFilter(request,response);
        }*/
    }
}
